import HandleBtn from '@/components/HandleBar/btn';
import { ProTable, type ProColumns } from '@/components/Pro';
import {
  historyDataControllerHistoryDataExport as exportDataReport,
  historyDataControllerMeterDataPage,
} from '@/services/ess/historicalData';
import { downloadFetch } from '@/utils/downloadFile';
import { Link, useIntl } from '@umijs/max';
import { message } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import React, { useEffect, useState } from 'react';

interface Props {
  tabIndex?: string;
  deviceCode?: string;
  deviceType?: string;
  areaId?: string;
  selectedKeys?: string[];
}

const MeterDetails: React.FC<Props> = ({ deviceCode, deviceType, areaId, selectedKeys }) => {
  const intl = useIntl(); // 获取国际化实例

  const [data, setData] = useState<API.MeterRealTimeData[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [params, setParams] = useState({
    current: 1,
    pageSize: 20,
    startDate: dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss'),
    endDate: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
  });

  const [columns, setColumns] = useState<ProColumns<API.MeterRealTimeData>[]>([]);

  const initialColumns: ProColumns<any>[] = [
    {
      title: intl.formatMessage({ id: 'data.s/N' }), // 序号
      key: 'index',
      valueType: 'index',
      width: 60,
      dataIndex: 'pageIndex',
    },
    // {
    //   title: intl.formatMessage({ id: 'data.time' }), // 时间
    //   dataIndex: 'time',
    //   key: 'time',
    //   valueType: 'dateTimeRange',
    //   width: 200,
    //   initialValue: [dayjs().startOf('day'), dayjs()],
    //   render: (_, record) => {
    //     return <span>{record.time}</span>;
    //   },
    //   search: {
    //     transform: (value) => {
    //       return {
    //         startDate: value ? dayjs(value[0]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
    //         endDate: value ? dayjs(value[1]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
    //       };
    //     },
    //   },
    //   fieldProps: {
    //     onCalendarChange: (dates: [Dayjs, Dayjs]) => {
    //       if (dates && dates.length === 2) {
    //         const [start, end] = dates;
    //         if (dayjs(end).diff(start, 'day') > 31) {
    //           message.warning(intl.formatMessage({ id: 'data.sDays' }));
    //         }
    //       }
    //     },
    //     disabledDate: (current: Dayjs | null) => {
    //       return current && current > dayjs().endOf('day');
    //     },
    //   },
    // },
    {
      title: intl.formatMessage({ id: 'data.acquisitionTime' }), // 采集时间
      dataIndex: 'collectTime',
      key: 'collectTime',
      hideInSearch: false,
      valueType: 'dateTimeRange',
      initialValue: [dayjs().startOf('day'), dayjs()],
      render: (_, record) => {
        return <span>{record.collectTime}</span>;
      },
      search: {
        transform: (value) => {
          return {
            startDate: value ? dayjs(value[0]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
            endDate: value ? dayjs(value[1]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
          };
        },
      },
      fieldProps: {
        onCalendarChange: (dates: [Dayjs, Dayjs]) => {
          if (dates && dates.length === 2) {
            const [start, end] = dates;
            if (dayjs(end).diff(start, 'day') > 31) {
              message.warning(intl.formatMessage({ id: 'data.sDays' }));
            }
          }
        },
        disabledDate: (current: Dayjs | null) => {
          return current && current > dayjs().endOf('day');
        },
      },
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.reportingTime' }), // 上报时间
      dataIndex: 'reportTime',
      key: 'reportTime',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.gridFrequency' }), // 电网频率
      dataIndex: 'gridFreq',
      key: 'gridFreq',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.activeDemand' }), // 有功需量
      dataIndex: 'demand',
      key: 'demand',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.powerFactor' }), // 功率因数
      dataIndex: 'powerFactor',
      key: 'powerFactor',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.totalActivePowerKw' }), // 总有功功率
      dataIndex: 'activePower',
      key: 'activePower',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.totalReactivePowerKvar' }), // 总无功功率（kvar）
      dataIndex: 'reactivePower',
      key: 'reactivePower',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.totalApparentPowerKva' }), // 总视在功率（kVA）
      dataIndex: 'apparentPower',
      key: 'apparentPower',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.ia' }), // A相电流
      dataIndex: 'ia',
      key: 'ia',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.ib' }), // B相电流
      dataIndex: 'ib',
      key: 'ib',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.ic' }), // C相电流
      dataIndex: 'ic',
      key: 'ic',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.ua' }), // A相电压（V）
      dataIndex: 'ua',
      key: 'ua',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.ub' }), // B相电压（V）
      dataIndex: 'ub',
      key: 'ub',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.uc' }), // C相电压（V）
      dataIndex: 'uc',
      key: 'uc',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.totalEnergy' }), // 组合有功总电能
      dataIndex: 'combinedActiveTotal',
      key: 'combinedActiveTotal',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.sharpEnergy' }), // 组合有功尖电能
      dataIndex: 'combinedActiveTip',
      key: 'combinedActiveTip',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.peakEnergy' }), // 组合有功峰电能
      dataIndex: 'combinedActivePeak',
      key: 'combinedActivePeak',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.shoulderEnergy' }), // 组合有功平电能
      dataIndex: 'combinedActiveFlat',
      key: 'combinedActiveFlat',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.valleyEnergy' }), // 组合有功谷电能
      dataIndex: 'combinedActiveValley',
      key: 'combinedActiveValley',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.positive' }), // 正向有功总电能
      dataIndex: 'positiveActiveTotal',
      key: 'positiveActiveTotal',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.positiveSharpEnergy' }), // 正向有功尖电能
      dataIndex: 'positiveActiveTip',
      key: 'positiveActiveTip',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.positivePeakEnergy' }), // 正向有功峰电能
      dataIndex: 'positiveActivePeak',
      key: 'positiveActivePeak',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.positiveShoulderEnergy' }), // 正向有功平电能
      dataIndex: 'positiveActiveFlat',
      key: 'positiveActiveFlat',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.positiveValleyEnergy' }), // 正向有功谷电能
      dataIndex: 'positiveActiveValley',
      key: 'positiveActiveValley',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.reverseTotalEnergy' }), // 反向有功总电能
      dataIndex: 'reverseActiveTotal',
      key: 'reverseActiveTotal',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.reverseSharpEnergy' }), // 反向有功尖电能
      dataIndex: 'reverseActiveTip',
      key: 'reverseActiveTip',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.reversePeakEnergy' }), // 反向有功峰电能
      dataIndex: 'reverseActivePeak',
      key: 'reverseActivePeak',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.reverseShoulderEnergy' }), // 反向有功平电能
      dataIndex: 'reverseActiveFlat',
      key: 'reverseActiveFlat',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.reverseValleyEnergy' }), // 反向有功谷电能
      dataIndex: 'reverseActiveValley',
      key: 'reverseActiveValley',
      hideInSearch: true,
      width: 150,
    },
  ];

  const columnToAttrMap: Record<string, string> = {
    collectTime: 'ts', // 采集时间
    reportTime: 'reportTime', // 上报时间
    gridFreq: 'gridFreq', // 电网频率
    powerFactor: 'powerFactor', // 功率因数
    activePower: 'activePower', // 总有功功率
    reactivePower: 'reactivePower', // 总无功功率
    apparentPower: 'apparentPower', // 总视在功率

    // 电流相关
    ia: 'ia', // A相电流
    ib: 'ib', // B相电流
    ic: 'ic', // C相电流

    // 电压相关
    ua: 'ua', // A相电压
    ub: 'ub', // B相电压
    uc: 'uc', // C相电压

    // 组合有功电能
    combinedActiveTotal: 'combinedActiveTotal', // 组合有功总电能
    combinedActiveTip: 'combinedActiveTip', // 组合有功尖电能
    combinedActivePeak: 'combinedActivePeak', // 组合有功峰电能
    combinedActiveFlat: 'combinedActiveFlat', // 组合有功平电能
    combinedActiveValley: 'combinedActiveValley', // 组合有功谷电能

    // 正向有功电能
    positiveActiveTotal: 'positiveActiveTotal', // 正向有功总电能
    positiveActiveTip: 'positiveActiveTip', // 正向有功尖电能
    positiveActivePeak: 'positiveActivePeak', // 正向有功峰电能
    positiveActiveFlat: 'positiveActiveFlat', // 正向有功平电能
    positiveActiveValley: 'positiveActiveValley', // 正向有功谷电能
    // 反向有功电能
    reverseActiveTotal: 'reverseActiveTotal', // 反向有功总电能
    reverseActiveTip: 'reverseActiveTip', // 反向有功尖电能
    reverseActivePeak: 'reverseActivePeak', // 反向有功峰电能
    reverseActiveFlat: 'reverseActiveFlat', // 反向有功平电能
    reverseActiveValley: 'reverseActiveValley', // 反向有功谷电能
  };

  const fetchData = async (params: {
    current: number;
    pageSize: number;
    startDate: string;
    endDate: string;
  }) => {
    setLoading(true);
    const response = await historyDataControllerMeterDataPage({
      current: params.current,
      pageSize: params.pageSize,
      startDate: params.startDate,
      endDate: params.endDate,
      deviceCode,
      deviceType,
      areaId,
    });

    if (response.success && response.data) {
      // 1. 首先确定哪些列应该显示
      const availableColumns = new Set<string>();

      // 2. 遍历所有记录，找出所有非空的字段
      response.data.records?.forEach((record) => {
        Object.entries(record).forEach(([key, value]) => {
          if (value !== null && value !== '') {
            availableColumns.add(key);
          }
        });
      });

      // 3. 过滤列，保留必要的基础列和有数据的列
      const filteredColumns = initialColumns.filter((column) => {
        // 始终保留这些基础列
        if (['pageIndex', 'collectTime', 'reportTime'].includes(column.dataIndex as string)) {
          return true;
        }

        // 检查该列是否有数据
        const apiField = columnToAttrMap[column.dataIndex as string] || column.dataIndex;
        return availableColumns.has(apiField as string);
      });

      // 4. 设置列
      setColumns(filteredColumns);

      // 5. 映射数据
      const mappedData = (response.data.records || []).map((record, index) => ({
        pageIndex: (params.current - 1) * params.pageSize + index + 1,
        time: record.ts,
        collectTime: record.ts,
        reportTime: record.reportTime,
        gridFreq: record.gridFreq,
        demand: record.demand,
        powerFactor: record.powerFactor,
        activePower: record.activePower,
        reactivePower: record.reactivePower,
        apparentPower: record.apparentPower,
        ia: record.ia,
        ib: record.ib,
        ic: record.ic,
        ua: record.ua,
        ub: record.ub,
        uc: record.uc,
        combinedActiveTotal: record.combinedActiveTotal,
        combinedActiveTip: record.combinedActiveTip,
        combinedActivePeak: record.combinedActivePeak,
        combinedActiveFlat: record.combinedActiveFlat,
        combinedActiveValley: record.combinedActiveValley,
        positiveActiveTotal: record.positiveActiveTotal,
        positiveActiveTip: record.positiveActiveTip,
        positiveActivePeak: record.positiveActivePeak,
        positiveActiveFlat: record.positiveActiveFlat,
        positiveActiveValley: record.positiveActiveValley,
        reverseActiveTotal: record.reverseActiveTotal,
        reverseActiveTip: record.reverseActiveTip,
        reverseActivePeak: record.reverseActivePeak,
        reverseActiveFlat: record.reverseActiveFlat,
        reverseActiveValley: record.reverseActiveValley,
      }));
      setData(mappedData);
      setTotal(response.data.total || 0);
    } else {
      setData([]);
      setTotal(0);
      setColumns(initialColumns);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchData(params);
  }, [deviceCode, deviceType, areaId, params]);

  const handleTableChange = (pagination: { current: number; pageSize: number }) => {
    setParams((prevParams) => ({
      ...prevParams,
      current: pagination.current,
      pageSize: pagination.pageSize,
    }));
  };

  const handleSearch = (values: any) => {
    const startDate = dayjs(values.startDate);
    const endDate = dayjs(values.endDate);
    if (endDate.diff(startDate, 'day') > 31) {
      message.warning(intl.formatMessage({ id: 'data.sDays' }));
      return;
    }
    setParams((prevParams) => ({
      ...prevParams,
      startDate: values.startDate,
      endDate: values.endDate,
    }));
  };

  const handleReset = () => {
    setParams({
      current: params.current,
      pageSize: params.pageSize,
      startDate: dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss'),
      endDate: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
    });
    fetchData(params);
  };

  const scroll = {
    x: 'max-content',
    y: 'calc(100vh - 300px)',
  };

  const [selectedColumns, setSelectedColumns] = useState<string[]>([]);

  const exportDataReportFun = async (params: any) => {
    const startDate = dayjs(params.startDate);
    const endDate = dayjs(params.endDate);
    if (endDate.diff(startDate, 'day') > 3) {
      message.warning(intl.formatMessage({ id: 'data.selectTimeRange' }));
      return;
    }

    // 根据当前表格数据过滤出非空列
    const nonNullColumns = Object.keys(columnToAttrMap).filter((col) =>
      data.some((record) => record[col as keyof API.MeterRealTimeData] !== null),
    );

    // 使用过滤后的列或用户选择的列
    const attrNames =
      selectedColumns.length > 0
        ? selectedColumns
            .filter((col) => col !== 'index' && col !== 'pageIndex')
            .map((col) => columnToAttrMap[col] || col)
        : nonNullColumns.map((col) => columnToAttrMap[col]);

    const exportParams: API.HistoryDataQuery = {
      areaId: Number(areaId),
      deviceType,
      deviceCode,
      startDate: dayjs(params.startDate).format('YYYY-MM-DD HH:mm:ss'),
      endDate: dayjs(params.endDate).format('YYYY-MM-DD HH:mm:ss'),
      attrNames,
    };

    await downloadFetch(exportDataReport, exportParams);
  };

  return (
    <div>
      <ProTable
        headerTitle={intl.formatMessage({ id: 'data.meterDetails' })} // 电表详情
        search={{
          labelWidth: 80,
        }}
        columns={columns}
        scroll={scroll}
        pagination={{
          pageSize: params.pageSize,
          total,
          onChange: (page, pageSize) => handleTableChange({ current: page, pageSize }),
        }}
        dataSource={data}
        loading={loading}
        onSubmit={handleSearch}
        onReset={handleReset}
        columnsState={{
          value: Object.fromEntries(
            columns
              .filter((col) => col.dataIndex)
              .map((col) => [
                col.dataIndex,
                {
                  show:
                    selectedColumns.length === 0
                      ? true
                      : selectedColumns.includes(col.dataIndex as string),
                },
              ]),
          ),
          onChange: (stateMap) => {
            const newSelectedColumns = Object.entries(stateMap)
              // eslint-disable-next-line @typescript-eslint/no-unused-vars
              .filter(([_, value]) => value.show)
              .map(([key]) => key);
            setSelectedColumns(newSelectedColumns);
          },
        }}
        toolbar={{
          className: 'historyToobalr',
          actions: [
            <>
              <HandleBtn
                key="export"
                handleType="export"
                onClick={() => exportDataReportFun(params)}
              >
                {intl.formatMessage({ id: 'statistics.common.export' })}
              </HandleBtn>
              <Link key="monitor" to={`/stationmonitor/realtime?key=${selectedKeys}`}>
                {intl.formatMessage({ id: 'data.realtimeMonitor' })}
              </Link>
            </>,
          ],
        }}
      />
    </div>
  );
};

export default MeterDetails;
